layui.use(['form', 'layer'], function () {
    let $ = layui.$;
    let layer = layui.layer;
    // 加载表单组件
    let form = layui.form;
    // 定义输入框的前台校验
    form.verify({
        adminName: function (value, item) {
            if (value == ''){
                return '用户名不能为空';
            }
        },
        adminPwd: function (value, item) {
            if (value == ''){
                return '密码不能为空';
            }
        }
    });

    //监听提交
    form.on('submit(formDemo)', function (data) {
        let url = $("#loginForm").attr('action');
        let load = layer.load();
        let _token = $("input[name=_token]").val();
        data.field['_token'] = _token;
        $.ajax({
            url: url,
            type: 'post',
            data: data.field,
            dataType: 'json',
            before: function(){
                load;
            },
            success: function (res) {
                layer.close(load);
                if (res.code == 0){
                    tipMessage(res.msg, 6, function () {
                        location.href = '/';
                    });
                }else {
                    tipMessage(res.msg);
                }
            },
            error: function () {
                layer.close(load);
                tipMessage('服务器问题');
            }
        })
        // 组织submit的提交
        return false;
    });
});

function tipMessage(message, icon=5, obj='') {
    layui.use('layer', function () {
        let layer = layui.layer;
        if (obj !== ''){
            layer.msg(message, {icon: icon}, obj);
        }else {
            layer.msg(message, {icon: icon});
        }
    });
}
